package cn.yangliu.task.utils;

import cn.yangliu.task.entity.Task;
import cn.yangliu.task.entity.TaskVo;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author 杨柳
 * @date 2019-04-14
 */
public class TransformDataUtils {

    public static TaskVo getTransformData(Task task) {
        TaskVo taskVo = null;
        try {
            Class<TaskVo> clazz = TaskVo.class;
            taskVo = clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                String fieldName = field.getName();
                Field targetField = Task.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                targetField.setAccessible(true);

                Object value = targetField.get(task);
                field.set(taskVo, value);

                field.setAccessible(false);
                targetField.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return taskVo;
    }


    public static Task getTransformData(TaskVo taskVo) {
        Task task = new Task();
        try {
            Class<TaskVo> clazz = TaskVo.class;

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                String fieldName = field.getName();
                Field targetField = Task.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                targetField.setAccessible(true);

                Object value = field.get(taskVo);
                targetField.set(task, value);

                field.setAccessible(false);
                targetField.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return task;
    }
}
